package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrFormatter;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.jim.WebSocketMsgDTO;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.constants.SqfwCompleteflowConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.dto.SqfwCompleteFlowUpdateDTO;
import com.budwk.app.sqfw.enums.CompleteFlowFileTypeEnum;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.vo.SqfwCompleteFlowVO;
import com.budwk.app.util.AudioToTextUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@IocBean
@At("/platform/sqfw/completeflow")
@ApiDefinition(tag = "完结流程")
@Slf4j
public class SqfwCompleteflowController {
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SqfwWorkorderService sqfwWorkorderService;
    @Inject
    private SqfwCloudcallbackService sqfwCloudcallbackService;
    @Inject
    private SqfwWebSocket sqfwWebSocket;
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;
    @Inject
    private PropertiesProxy propertiesProxy;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询完结流程")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_completeflow.class
    )
    @SLog(tag = "分页查询完结流程")
    @ApiResponses(
            implementation = Sqfw_completeflow.class
    )
    public Result<?> list(@Param("..") Sqfw_completeflow bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("create_date", "asc");
        }

        if (bean.getSqfwId() != null && Strings.isNotBlank(bean.getSqfwId().toString())) {
            cnd.and("sqfwId", "=", bean.getSqfwId());
        }

        if (bean.getWorkerId() != null && Strings.isNotBlank(bean.getWorkerId().toString())) {
            cnd.and("workerId", "=", bean.getWorkerId());
        }

        if (bean.getFileType() != null && Strings.isNotBlank(bean.getFileType().toString())) {
            cnd.and("fileType", "=", bean.getFileType());
        }

        if (bean.getCreateDate() != null && Strings.isNotBlank(bean.getCreateDate().toString())) {
            cnd.and("createDate", "=", bean.getCreateDate());
        }

        if (bean.getResourcePath() != null && Strings.isNotBlank(bean.getResourcePath().toString())) {
            cnd.and("resourcePath", "=", bean.getResourcePath());
        }

        if (bean.getPosition() != null && Strings.isNotBlank(bean.getPosition().toString())) {
            cnd.and("position", "=", bean.getPosition());
        }

        if (bean.getRemark() != null && Strings.isNotBlank(bean.getRemark().toString())) {
            cnd.and("remark", "=", bean.getRemark());
        }

        if (bean.getPhone() != null && Strings.isNotBlank(bean.getPhone().toString())) {
            cnd.and("phone", "=", bean.getPhone());
        }

        if (bean.getUserId() != null && Strings.isNotBlank(bean.getUserId().toString())) {
            cnd.and("userId", "=", bean.getUserId());
        }

        if (bean.getUserName() != null && Strings.isNotBlank(bean.getUserName().toString())) {
            cnd.and("userName", "=", bean.getUserName());
        }

        if (bean.getText() != null && Strings.isNotBlank(bean.getText().toString())) {
            cnd.and("text", "=", bean.getText());
        }
        cnd.orderBy("create_date", "desc");

        Pagination pagination = sqfwCompleteflowService.listPage(pageNo, pageSize, cnd);
        List<Sqfw_completeflow> list = pagination.getList(Sqfw_completeflow.class);

        List<SqfwCompleteFlowVO> dataList = Lists.newArrayList();
        for (Sqfw_completeflow completeFlow : list) {
            SqfwCompleteFlowVO vo = new SqfwCompleteFlowVO();
            BeanUtil.copyProperties(completeFlow, vo);

            // wzy 2023-11-13 使用配置的方式拼出路径交给前端
            if (StringUtils.isNotBlank(vo.getResourcePath())) {
                if (vo.getResourcePath().startsWith("/"))
                    vo.setResourcePathUrl(NutzIocUtils.getOssPrefix() + vo.getResourcePath());
                else vo.setResourcePathUrl(vo.getResourcePath());
            }
            if (vo.getFileType().contains("录音") && StringUtils.isNotBlank(vo.getText())) {
                vo.setText(AudioToTextUtils.replaceMsgContent(completeFlow.getText()));
            }
            dataList.add(vo);
        }
        pagination.setList(dataList);

        return Result.data(pagination);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增工作流")
    @ApiFormParams(
            implementation = Sqfw_completeflow.class
    )
    @ApiResponses
    @SLog(tag = "新增工作流", value = "${args[0]}")
    public Result<?> create(@Param("..") SqfwCompleteFlowUpdateDTO sqfwCompleteFlowUpdateDTO, HttpServletRequest req) {

        Sqfw_completeflow completeFlow = new Sqfw_completeflow();
        BeanUtil.copyProperties(sqfwCompleteFlowUpdateDTO, completeFlow);
        completeFlow.setCreateDate(new Date());

        Boolean cloudTransFlag = sqfwCompleteFlowUpdateDTO.getCloudTransFlag();
        cloudTransFlag = cloudTransFlag == null;
        if (!cloudTransFlag) {
            completeFlow.setText(sqfwCompleteFlowUpdateDTO.getLocalAudioTransText());
        }
        Sqfw_completeflow insertCompleteFlow = sqfwCompleteflowService.insert(completeFlow);

        String fileType = insertCompleteFlow.getFileType();
        if (fileType.contains("录音")) {
            sqfwCompleteFlowUpdateDTO.setId(insertCompleteFlow.getId());
            handelAudioTrans(sqfwCompleteFlowUpdateDTO);
        }

        // 更新工单表中的最新工作流备注
        if (StringUtils.isNotBlank(sqfwCompleteFlowUpdateDTO.getLatestFlowRemark())) {
            String latestFlowRemark = sqfwCompleteFlowUpdateDTO.getLatestFlowRemark();

            if (latestFlowRemark.equals("完成了文档")) {
                // 如果是完成了文档需要统计一下当前一共完成了几个文档
                Cnd countCnd = Cnd.NEW();
                countCnd.and("service_type", "=", completeFlow.getFileType())
                        .and("worker_id", "=", completeFlow.getWorkerId()).and("delflag", "=", false);
                int count = sqfwWorkorderService.count(countCnd) + 1;
                latestFlowRemark = StrFormatter.format("完成了{}份文档", count);
            }

            String workerId = insertCompleteFlow.getWorkerId();
            Sqfw_workorder updateWorkOrder = new Sqfw_workorder();
            updateWorkOrder.setId(workerId);
            updateWorkOrder.setLatestFlowRemark(latestFlowRemark);
            sqfwWorkorderService.updateIgnoreNull(updateWorkOrder);

            // 查询该工作流转发人的id
            String sqfwId = insertCompleteFlow.getSqfwId();
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            String serviceOrderUserId = serviceRecord.getCreatedBy();
            sqfwWebSocket.sendMessage(serviceOrderUserId, new WebSocketMsgDTO(SqfwWebSocketMsgConstants.work_flow_created, "工作流节点已经更新"));

        }
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改工作流")
    @ApiFormParams(
            implementation = Sqfw_completeflow.class
    )
    @ApiResponses
    @SLog(tag = "修改工作流", value = "${args[0]}")
    public Result<?> updateFlow(@Param("..") SqfwCompleteFlowUpdateDTO sqfwCompleteFlowUpdateDTO, HttpServletRequest req) {
        Sqfw_completeflow updateCompleteFlow = sqfwCompleteflowService.fetch(Cnd.where(Sqfw_completeflow::getId,"=",sqfwCompleteFlowUpdateDTO.getId()));

        String type =sqfwCompleteFlowUpdateDTO.getFileType();
        switch (type){
            case SqfwCompleteflowConstants.FILE_TYPE_TEXT:updateCompleteFlow.setText(sqfwCompleteFlowUpdateDTO.getText());
            break;
            case SqfwCompleteflowConstants.FILE_TYPE_IMAGE:updateCompleteFlow.setResourcePath(sqfwCompleteFlowUpdateDTO.getResourcePath());
            break;
        }
        sqfwCompleteflowService.updateIgnoreNull(updateCompleteFlow);
        return Result.success(updateCompleteFlow);
    }





    /**
     * wzy 2023-11-28 语音识别现在需要调用调用手机本地模型进行处理
     *
     * @param flowDTO 工作流DTO
     */
    private void handelAudioTrans(SqfwCompleteFlowUpdateDTO flowDTO) {
        Boolean cloudTransFlag = flowDTO.getCloudTransFlag();
        cloudTransFlag = cloudTransFlag == null;
        if (cloudTransFlag) {
            sqfwCompleteflowService.transferFlowAudioToText(flowDTO.getId());
        } else {
            Sqfw_cloudcallback cloudCallBack = new Sqfw_cloudcallback();
            cloudCallBack.setAudioUrl(flowDTO.getResourcePath());
            cloudCallBack.setText(flowDTO.getLocalAudioTransText()); // 这个字段存已经通过系统替换过的文本
            cloudCallBack.setResultDetail(flowDTO.getLocalAudioTransOriText());
            cloudCallBack.setBusinessId(flowDTO.getId());
            cloudCallBack.setBusinessType(SqfwCloudBusinessConstants.FLOW);
            cloudCallBack.setCreatedAt(new Date().getTime());
            cloudCallBack.setUpdatedAt(new Date().getTime());
            cloudCallBack.setDelFlag(false);
            cloudCallBack.setTransChannel(SqfwCloudBusinessConstants.TRANS_CHANNEL_DFSJ);
            sqfwCloudcallbackService.insert(cloudCallBack);
        }
    }


    @At("/multiCreate")
    @Ok("json")
    @POST
    @ApiOperation(name = "新增多个工作流")
    @ApiFormParams(
            implementation = Sqfw_completeflow.class
    )
    @ApiResponses
    @SLog(tag = "新增多个工作流", value = "${args[0]}")
    public Result<?> multiCreate(@Param("..") SqfwCompleteFlowUpdateDTO sqfwCompleteFlowUpdateDTO, HttpServletRequest req) {

        Sqfw_completeflow completeFlow = new Sqfw_completeflow();
        BeanUtil.copyProperties(sqfwCompleteFlowUpdateDTO, completeFlow);
        completeFlow.setCreateDate(new Date());

        if (StringUtils.isNotBlank(sqfwCompleteFlowUpdateDTO.getResourcePath())) {
            if (StringUtils.isNotBlank(sqfwCompleteFlowUpdateDTO.getFileType())) {
                List<String> pathList = Lists.newArrayList(sqfwCompleteFlowUpdateDTO.getResourcePath().split(","));
                List<String> typeList = Lists.newArrayList(sqfwCompleteFlowUpdateDTO.getFileType().split(","));
                for (int i = 0; i < pathList.size(); i++) {
                    completeFlow.setResourcePath(pathList.get(i));
                    completeFlow.setFileType(typeList.get(i));
                    Sqfw_completeflow insertCompleteFlow = sqfwCompleteflowService.insert(completeFlow);
                    String fileType = insertCompleteFlow.getFileType();
                    if (fileType.contains(CompleteFlowFileTypeEnum.SOUND_RECORD.getName())) {
                        sqfwCompleteflowService.transferFlowAudioToText(insertCompleteFlow.getId());
                    }

                    // 更新工单表中的最新工作流备注
                    sqfwWorkorderService.updateLatestFlowRemarkWithCompleteFlow(completeFlow.getWorkerId(),
                            sqfwCompleteFlowUpdateDTO.getFileType(), true);
                }
            }
        }
        if (StringUtils.isNotBlank(sqfwCompleteFlowUpdateDTO.getText())) {
            completeFlow.setText(sqfwCompleteFlowUpdateDTO.getText());
            sqfwCompleteflowService.insert(completeFlow);
        }

        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改完结流程")
    @ApiFormParams(
            implementation = Sqfw_completeflow.class
    )
    @ApiResponses
    @SLog(tag = "修改完结流程", value = "${args[0]}")
    @SaCheckPermission("sqfw.completeflow.update")
    public Result<?> update(@Param("..") SqfwCompleteFlowUpdateDTO sqfwCompleteflow, HttpServletRequest req) {
        //sqfwCompleteflow.setUpdatedBy(SecurityUtil.getUserId());
        sqfwCompleteflowService.updateIgnoreNull(sqfwCompleteflow);

        // 更新工单表中的最新工作流备注
        if (StringUtils.isNotBlank(sqfwCompleteflow.getLatestFlowRemark())) {
            String workerId = sqfwCompleteflow.getWorkerId();
            Sqfw_workorder updateWorkOrder = new Sqfw_workorder();
            updateWorkOrder.setId(workerId);
            updateWorkOrder.setLatestFlowRemark(sqfwCompleteflow.getLatestFlowRemark());
            sqfwWorkorderService.updateIgnoreNull(updateWorkOrder);
        }

        return Result.success();
    }


    @At("/deleteFlowComplete")
    @Ok("json")
    @POST
    @ApiOperation(name = "修改完结流程")
    @ApiFormParams(
            implementation = Sqfw_completeflow.class
    )
    @ApiResponses
    @SLog(tag = "修改完结流程", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> deleteFlowComplete(@Param("..") SqfwCompleteFlowUpdateDTO sqfwCompleteflow, @Param("fileType") String fileType, HttpServletRequest req) {
        sqfwCompleteflowService.delete(sqfwCompleteflow.getId());

        // 更新工单表中的最新工作流备注
        Cnd cnd = Cnd.NEW();
        cnd.and("id", "=", sqfwCompleteflow.getWorkerId());
        Sqfw_workorder sqfw_workorder = sqfwWorkorderService.fetch(cnd);
        if (sqfw_workorder != null) {
            sqfw_workorder.setId(sqfwCompleteflow.getWorkerId());
            sqfw_workorder.setWk_status("new");
            sqfw_workorder.setComplete_time(null);
            sqfw_workorder.setRemark(null);
            sqfw_workorder.setLatestFlowRemark(sqfwCompleteflow.getLatestFlowRemark());


            sqfwWorkorderService.updateLatestFlowRemarkWithCompleteFlow(sqfw_workorder, sqfwCompleteflow.getLatestFlowRemark(), fileType, false);
        }
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取完结流程")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "根据ID获取完结流程", value = "${args[0]}")
    // @SaCheckPermission("sqfw.completeflow")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(id);
        if (sqfwCompleteflow == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }

        SqfwCompleteFlowVO vo = new SqfwCompleteFlowVO();
        BeanUtil.copyProperties(sqfwCompleteflow, vo);

        if (StringUtils.isNotBlank(vo.getResourcePath())) {
            if (vo.getResourcePath().startsWith("/"))
                vo.setResourcePathUrl(NutzIocUtils.getOssPrefix() + vo.getResourcePath());
            else vo.setResourcePathUrl(vo.getResourcePath());

            // 上线之后就删掉下面这一句话
            //vo.setResourcePath(vo.getResourcePathUrl());
        }
        return Result.data(vo);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除完结流程")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除完结流程", value = "${args[0]}")
    @SaCheckPermission("sqfw.completeflow.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(id);
        if (sqfwCompleteflow == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCompleteflowService.delete(id);

        Sqfw_formSummary formSummary = sqfwFormSummaryService.fetch(Cnd.where("sqfw_flow_id", "=", id));
        if (formSummary != null)
            sqfwFormSummaryService.delete(formSummary.getId());

        req.setAttribute("_slog_msg", sqfwCompleteflow.getId());
        return Result.success();
    }

    @At("/deleteAndUpdateWO")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除通讯服务记录")
    @SLog(tag = "删除通讯服务记录", value = "${args[0]}")
    public Result<?> deleteAndUpdateWO(@Param("id") String id, HttpServletRequest req) {
        sqfwCompleteflowService.deleteAndUpdateWO(id);
        req.setAttribute("_slog_msg", id);
        return Result.success();
    }

    @At("/transferFlowAudioToText")
    @Ok("json")
    @GET
    @ApiOperation(name = "工作流语音转文字")
    @SLog(tag = "根据ID获取完结流程", value = "${args[0]}")
    public Result<?> transferFlowAudioToText(@Param("id") String id, HttpServletRequest req) {

        Sqfw_completeflow completeFlow = sqfwCompleteflowService.fetch(id);
        if (completeFlow == null) return Result.error("数据不存在");
        if (!completeFlow.getFileType().contains("录音")) return Result.error("该类型文件不支持");
        completeFlow.setText("");
        sqfwCompleteflowService.updateIgnoreNull(completeFlow);

        int successCount = sqfwCompleteflowService.transferFlowAudioToText(id);

        return Result.success(successCount);
    }

    @At("/flowTakeAPatSms")
    @Ok("json")
    @POST
    @ApiOperation(name = "工作流中的拍一拍发送短信功能")
    @SaCheckLogin
    @SLog("工作流中的拍一拍发送短信功能")
    public Result<?> flowTakeAPatSms(@Param("serviceOrderId") String serviceOrderId, @Param("serviceUserId") String serviceUserId) {
        int smsCount = sqfwCompleteflowService.flowTakeAPatSms(serviceOrderId, serviceUserId);
        return Result.success(smsCount);
    }

    @At("/getFireHiddenPDFByPhoneNo")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据手机号查询消防安全排查 主要供给祥云小程序调用")
    @SLog(tag = "根据手机号查询消防安全排查", value = "${args[0]}")
    public Result<?> getFireHiddenPDFByPhoneNo(@Param("phoneNo") String phoneNo, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize) {
        Pagination list = sqfwCompleteflowService.getFireHiddenPDFByPhoneNo(phoneNo, pageNo, pageSize);
        return Result.success(list);
    }

    @At("/getForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取完结流程")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "根据id获取完结流程", value = "${args[0]}")
    public Result<?> getForBM(@Param("id") String id, HttpServletRequest req) {
        Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(id);
        if (sqfwCompleteflow == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(sqfwCompleteflow);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询pdf列表")
    @ApiResponses(
            implementation = Sqfw_completeflow.class
    )
    public Result<?> listPdf(@Param("serviceType") String serviceType, @Param("fillDate") String fillDate, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize) {
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_completeflow::getUserId, "=", SecurityUtil.getUserId());
        cnd.and(Sqfw_completeflow::getFileType, "=", serviceType);
        cnd.and(Sqfw_completeflow::getCreateDate, ">", fillDate);
        cnd.and(Sqfw_completeflow::getCreateDate, "<", fillDate + "-31 23:59:59");
        cnd.asc(Sqfw_completeflow::getCreateDate);


        Pagination pagination = sqfwCompleteflowService.listPage(pageNo, pageSize, cnd);
        List<Sqfw_completeflow> list = pagination.getList(Sqfw_completeflow.class);

        List<SqfwCompleteFlowVO> dataList = Lists.newArrayList();
        for (Sqfw_completeflow completeFlow : list) {
            SqfwCompleteFlowVO vo = new SqfwCompleteFlowVO();
            BeanUtil.copyProperties(completeFlow, vo);

            // wzy 2023-11-13 使用配置的方式拼出路径交给前端
            if (StringUtils.isNotBlank(vo.getResourcePath())) {
                if (vo.getResourcePath().startsWith("/"))
                    vo.setResourcePathUrl(NutzIocUtils.getOssPrefix() + vo.getResourcePath());
                else vo.setResourcePathUrl(vo.getResourcePath());
            }
            if (vo.getFileType().contains("录音") && StringUtils.isNotBlank(vo.getText())) {
                vo.setText(AudioToTextUtils.replaceMsgContent(completeFlow.getText()));
            }
            dataList.add(vo);
        }
        pagination.setList(dataList);

        return Result.data(pagination);
    }
}
